package com.klm.common.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Component
public class HttpUtils {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 发送 GET 请求
     *
     * @param url 请求的 URL
     * @param headers 请求头
     * @param params 查询参数
     * @return 响应的字符串内容
     */
    public String get(String url, Map<String, String> headers, Map<String, String> params) {
        // 构建请求 URL
        StringBuilder urlBuilder = new StringBuilder(url);
        if (params != null && !params.isEmpty()) {
            urlBuilder.append("?");
            params.forEach((key, value) -> urlBuilder.append(key).append("=").append(value).append("&"));
            // 去掉最后一个多余的 "&"
            urlBuilder.setLength(urlBuilder.length() - 1);
        }

        // 构建请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        if (headers != null) {
            headers.forEach(httpHeaders::add);
        }

        // 创建请求实体
        HttpEntity<String> requestEntity = new HttpEntity<>(httpHeaders);

        // 发送 GET 请求
        ResponseEntity<String> response = restTemplate.exchange(
                urlBuilder.toString(),
                HttpMethod.GET,
                requestEntity,
                String.class
        );

        // 检查响应状态码
        if (response.getStatusCode().is2xxSuccessful()) {
            return response.getBody();
        } else {
            // 使用 HttpStatusCode 对象获取状态码
            HttpStatusCode statusCode = response.getStatusCode();
            throw new RuntimeException("HTTP 请求失败，状态码：" + statusCode.value());
        }
    }

    /**
     * 发送 POST 请求
     *
     * @param url 请求的 URL
     * @param headers 请求头
     * @param body 请求体
     * @return 响应的字符串内容
     */
    public String post(String url, Map<String, String> headers, Object body) {
        // 构建请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        if (headers != null) {
            headers.forEach(httpHeaders::add);
        }

        // 创建请求实体
        HttpEntity<Object> requestEntity = new HttpEntity<>(body, httpHeaders);

        // 发送 POST 请求
        ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.POST,
                requestEntity,
                String.class
        );

        // 检查响应状态码
        if (response.getStatusCode().is2xxSuccessful()) {
            return response.getBody();
        } else {
            // 使用 HttpStatusCode 对象获取状态码
            HttpStatusCode statusCode = response.getStatusCode();
            throw new RuntimeException("HTTP 请求失败，状态码：" + statusCode.value());
        }
    }
}
